package yagwl.server.fnd;

import java.util.logging.Logger;

import yagwl.client.model.fnd.SessionDto;
import yagwl.client.model.fnd.SessionRpcService;
import yagwl.service.util.svc.Context;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class SessionRpcServiceImpl extends RemoteServiceServlet implements
    SessionRpcService {

  private static final Logger log = Logger
      .getLogger(SessionRpcServiceImpl.class.getName());

  @Override
  public SessionDto getSession() {
    log.info("SessionDto.getSession Entry");
    SessionDto ses = new SessionDto();
    fillUserAttributes(ses);
    return ses;
  }

  protected void fillUserAttributes(SessionDto ses) {
    UserService userService = UserServiceFactory.getUserService();
    Context ctx = Context.getCurrentInstance();

    if (!ctx.isUserLoggedIn()) {
      ses.setLoginURL(userService.createLoginURL(getLoginTarget()));
      return;
    }

    ses.setLogoutURL(userService.createLogoutURL(getLogoutTarget()));
    ses.setUserLoggedIn(true);
    ses.setUserAdmin(userService.isUserAdmin());
    ses.setEmail((String) ctx.getAttribute(Context.Attr.Email.toString()));
    ses.setNickname((String) ctx.getAttribute(Context.Attr.Nickname.toString()));
    ses.setUserId(ctx.getUserId());

    log.info("SessionDto: " + ses.getEmail() + " " + ses.getNickname() + " "
        + ses.getUserId());
  }

  protected String getLoginTarget() {
    return "/yagwl.html";
  }

  protected String getLogoutTarget() {
    return "/yagwl.html";
  }

}
